package com.yc.net;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class URLDemo {

    public static void main(String[] args) throws IOException {

        downfile("http://www.hyycinfo.com/index.html?a=100&b=abc#xyz",
                "D:\\_文件柜\\133\\0924");

    }

    void url() throws IOException {
        URL url = new URL("http://www.hyycinfo.com/a/b/index.html?a=100&b=abc#xyz");

        System.out.println("url.getProtocol() = " + url.getProtocol());
        System.out.println("url.getHost() = " + url.getHost());
        System.out.println("url.getPort() = " + url.getPort());
        System.out.println("url.getPath() = " + url.getPath());
        System.out.println("url.getFile() = " + url.getFile());
        System.out.println("url.getQuery() = " + url.getQuery());

        URLConnection urlConnection = url.openConnection();
        System.out.println("urlConnection = " + urlConnection);
        System.out.println("文件编码 urlConnection.getContentEncoding() = " + urlConnection.getContentEncoding());
        System.out.println("文件大小 urlConnection.getContentLengthLong() = " + urlConnection.getContentLengthLong());

        InputStream in = urlConnection.getInputStream();

//        byte[] bytes = new byte[100];
//        int count;
//        while ((count=in.read(bytes))>0){
//            String s = new String(bytes,0,count);
//            System.out.print(s);
//        }

        // 字节流 转 字符流
        // InputStreamReader 处理流  看构造函数参数类型
        InputStreamReader isr = new InputStreamReader(in, "utf-8");
        // 可以按行读取的字符流
        BufferedReader br = new BufferedReader(isr);
        // java流的设计模式: 装饰器模式

        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        in.close();
    }

    /**
     * 下载文档到指定目录
     *
     * @param address
     * @param dir
     */
    public static void downfile(String address, String dir) throws IOException {
        URL url = new URL(address);
        URLConnection urlConnection = url.openConnection();
        // 提取文件名
        String path = url.getPath();
        String filename = path.replaceAll(".*/([^/]+)", "$1");
        // filename = index.html
        String filepath = dir + "/" + filename;

        try (InputStream in = urlConnection.getInputStream();
             FileOutputStream fos = new FileOutputStream(filepath)) {
            byte[] bytes = new byte[1024];
            int count;
            while ((count = in.read(bytes)) > 0) {
                fos.write(bytes, 0, count);
            }
        }

        System.out.printf("下载 %s 到 %s\n", address, filepath);
    }
}

